package com.zkdcloud.aspectInterceptor.advice;

import com.xdja.interceptor.advice.HttpAdvice;
import com.xdja.interceptor.exception.InvokeException;
import com.xdja.interceptor.util.ValidateUtils;
import com.zkdcloud.domain.Admin;
import com.zkdcloud.domain.User;
import com.zkdcloud.util.ResponseAndroidUtil;
import com.zkdcloud.util.TokenUtil;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

import static com.zkdcloud.constant.Constants.HTTP_CONSTANTS.REQUEST_ADMIN;
import static com.zkdcloud.constant.Constants.HTTP_CONSTANTS.REQUEST_USER;

/**
 * token校验
 *
 * @author zk
 * @since 2018/5/2
 */
@Component
public class MobileTokenAdvice implements HttpAdvice {
    public static final String HEADER_TOKEN = "Authorization";

    @Override
    public void doAdvice(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Map<String, Object> map) throws InvokeException {
        String token = httpServletRequest.getHeader(HEADER_TOKEN);
        try {
            if (token != null) {
                String realToken = token.substring(7, token.length());

                User user = TokenUtil.getTokenUser(realToken);
                httpServletRequest.setAttribute(REQUEST_USER, user);
                map.put(REQUEST_USER, user);
            }
        } catch (Exception e) {
            ResponseAndroidUtil.responseError("账号或密码错误，请重新登录",httpServletResponse);
        }
    }
}
